﻿
using System;

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

using zijian666.WebApi.JsonOption;

namespace zijian666.WebApi
{
    public partial class WebApiOptions
    {

        /// <summary>
        /// 启用标准化JSON的功能
        /// <br>formatName: 命名方式改为小于+下划线 如 RequestId -> request_id</br>
        /// <br>formatDateTime: 时间格式固定为 yyyy-MM-dd HH:mm:ss</br>
        /// </summary>
        public Action<Action<JsonOptions>> EnableJsonStandardized(bool formatName = true, bool formatDateTime = true)
        {
            MvcBuilder.AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.MaxDepth = 16;
                options.JsonSerializerOptions.IgnoreNullValues = true;
                //格式化属性命名
                if (formatName)
                {
                    options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                    options.JsonSerializerOptions.PropertyNamingPolicy = JsonNameLowercasePolicy.LowerCase;
                }
                //设置时间格式
                if (formatDateTime)
                {
                    options.JsonSerializerOptions.Converters.Add(JsonConverters.DateTime);
                    options.JsonSerializerOptions.Converters.Add(JsonConverters.DateTimeOffse);
                    options.JsonSerializerOptions.Converters.Add(JsonConverters.Timespan);
                }
            });
            return handler => MvcBuilder.AddJsonOptions(handler);
        }

    }
}
